package com.ib.review.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ib.review.base.result.DataResult;
import com.ib.review.constant.QaCacheConstant;
import com.ib.review.mapper.UserMapper;
import com.ib.review.pojo.po.UserInfoDO;
import com.ib.review.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Objects;

/**
 * @author ldw
 * 2024/01/24 22:21
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public DataResult<UserInfoDO> find(String account) {
        return DataResult.of(userMapper.selectById(account));
    }

    @Override
    public DataResult create(UserInfoDO userInfoDO) {
        userInfoDO.setCreateTime(new Timestamp(System.currentTimeMillis()));
        userInfoDO.setUserPwd(SaSecureUtil.rsaEncryptByPublic(QaCacheConstant.PUBLIC_KEY, userInfoDO.getUserPwd()));
        return DataResult.of(userMapper.insert(userInfoDO));
    }

    @Override
    public int updateErrorNum(String userAccount) {
        UserInfoDO userPo = userMapper.selectById(userAccount);
        UpdateWrapper<UserInfoDO> updateWrapper = new UpdateWrapper<>();
        int errNum = Objects.isNull(userPo.getErrorNum()) ? 0 : userPo.getErrorNum();
        updateWrapper.set("error_num", errNum + 1);
        updateWrapper.eq("user_account", userAccount);
        userMapper.update(null, updateWrapper);
        return 4 - errNum;
    }

    @Override
    public void resetErrorNum(String userAccount) {
        UpdateWrapper<UserInfoDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("error_num", 0);
        updateWrapper.eq("user_account", userAccount);
        userMapper.update(null, updateWrapper);
    }

    @Override
    public void modifyAreaCode(String userAccount, String areaCode) {
        UpdateWrapper<UserInfoDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("area_code", areaCode);
        updateWrapper.eq("user_account", userAccount);
        userMapper.update(null, updateWrapper);
    }
}
